﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Reflection;

namespace JY.Common.Helpers
{
    /// <summary>
    /// ConfigurationManager帮助类
    /// </summary>
    public static class ConfigurationManagerHelper
    {
        #region # 将AppSettings填充到类型中——void AutoFillAppSettingsToClass(Type type)
        /// <summary>
        /// 将AppSettings填充到类型中
        /// </summary>
        public static void AutoFillAppSettingsToClass(Type type)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Static);
            foreach (string appSetting in appSettings)
            {
                PropertyInfo propertyInfo = properties.FirstOrDefault(x => x.Name == appSetting);
                if (propertyInfo != null)
                {
                    if (propertyInfo.PropertyType == typeof(double))
                    {
                        double doubleResult = 0.0;
                        double.TryParse(ConfigurationManager.AppSettings[appSetting], out doubleResult);
                        propertyInfo.SetValue(type.GetField(appSetting), doubleResult);
                    }
                    else if (propertyInfo.PropertyType == typeof(bool))
                    {
                        bool boolResult = false;
                        bool.TryParse(ConfigurationManager.AppSettings[appSetting], out boolResult);

                        propertyInfo.SetValue(type.GetField(appSetting), boolResult);
                    }
                    else if (propertyInfo.PropertyType == typeof(int))
                    {
                        int intResult = 0;
                        int.TryParse(ConfigurationManager.AppSettings[appSetting], out intResult);
                        propertyInfo.SetValue(type.GetField(appSetting), intResult);
                    }
                    else if (propertyInfo.PropertyType == typeof(string))
                    {
                        propertyInfo.SetValue(type.GetField(appSetting), ConfigurationManager.AppSettings[appSetting]);
                    }
                }
            }

        }
        #endregion
    }
}
